const base = require("./base");
const moment = require("moment");

module.exports = class extends base {
    async _initialize() {
        await super.isCustomAuth();
    }

    /**
     *
     * @api {get} /home/app/index 获取应用列表
     * @apiDescription 获取应用列表
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户登录授权token.
     *
     * @apiParam {Number} template_id 模版id
     * @apiParam {String} keyword 关键词
     * @apiParam {Number} page 页码
     *
     * @apiSuccess {Array} success 应用列表
     *
     * @apiSampleRequest /home/app/index
     *
     */
    async index() {
        const { page = 1, keyword = "", template_id = 0 } = this.query;
        const customId = this.state.custom.id;

        const apps = await this.model("app")
            .query(qb => {
                qb.where("status", 1);
                qb.where("custom_id", "=", customId);

                if (keyword) {
                    qb.where("name", "like", `%${keyword}%`);
                }
                if (template_id) {
                    qb.where("template_id", template_id);
                }
                qb.orderBy("id", "desc");
            })
            .fetchPage({
                page: page,
                pageSize: 16,
                withRelated: [
                    "template",
                    {
                        wxa: qb => {
                            qb.where("status", 1);
                            qb.where("authorized", 1);
                        }
                    }
                ]
            });

        for (const app of apps.data) {
            app.AppToken = this.jwtSign({
                id: app.id,
                custom_id: app.custom_id,
                name: app.name
            });

            if (app.wxa.authorizer_appid) {
                app.wxa.WxaToken = this.jwtSign({
                    id: app.wxa.id,
                    app_id: app.wxa.app_id,
                    authorizer_appid: app.wxa.authorizer_appid,
                    nick_name: app.wxa.nick_name
                });
            }
        }

        this.success(apps);
    }

    /**
     *
     * @api {get} /home/template/index 获取模版列表
     * @apiDescription 获取模版列表
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiSuccess {Array} success 模版列表
     *
     * @apiSampleRequest /home/template/index
     *
     */
    async template() {
        const template = await this.model("template")
            .query(qb => {
                qb.where("status", 1);
                qb.orderBy("rank", "desc");
            })
            .fetchAll();

        this.success(template);
    }

    /**
     *
     * @api {get} /home/template/free 抢购免费应用
     * @apiDescription 抢购免费应用
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiSuccess {String} success FreeToken
     *
     * @apiSampleRequest /home/template/free
     *
     */
    async free() {
        const { template_id = 0 } = this.query;
        let free = await this.redis.getAsync(`template:free:${template_id}`);
        if (free && free > 0) {
            const locked = await this.lock(
                `lock:free:custom:${this.state.custom.id}`,
                3600 * 2
            );
            if (locked) {
                const pttl = await this.redis.pttlAsync(
                    `template:free:${template_id}`
                );
                await this.redis.setAsync(
                    `template:free:${template_id}`,
                    --free,
                    "EX",
                    parseInt(pttl / 1000)
                );
                this.success(this.jwtSign({}, "10m"), "抢购成功");
            } else {
                this.fail("您已参与今天抢购，每天仅支持抢购一次");
            }
        } else {
            this.fail("抢光了，请联系青妹（微信：qfxcx66），明天10点再来吧");
        }
    }

    /**
     *
     * @api {get} /home/app/freeTip 获取免费剩余
     * @apiDescription 获取免费剩余
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiSampleRequest /home/app/freeTip
     *
     */
    async freeTip() {
        // redis bug
        const keys = await this.redis.keysAsync(
            `${process.env.REDIS_PREFIX}template:free:*`
        );
        const free = {};
        const length = `${process.env.REDIS_PREFIX}template:free:`.length;
        for (const key of keys) {
            free[key.substr(length)] = await this.redis.getAsync(
                `template:free:${key.substr(length)}`
            );
        }
        this.success(free);
    }

    /**
     *
     * @api {post} /home/app/create 创建应用
     * @apiDescription 创建应用
     * @apiGroup Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     *
     * @apiParam {String} name 名称
     * @apiParam {String} info 简介
     * @apiParam {Number} template_industry_id 行业id
     * @apiParam {String} province 省
     * @apiParam {String} city 市
     * @apiParam {String} district 区
     *
     * @apiSampleRequest /home/app/create
     *
     */
    async create() {
        const {
            name,
            info,
            template_industry_id = 0,
            template_id = 0,
            province,
            city,
            district
        } = this.post;
        const customId = this.state.custom.id;

        const started_at = moment().format("YYYY-MM-DD HH:mm:ss");
        const ended_at = moment()
            .add(7, "days")
            .format("YYYY-MM-DD HH:mm:ss");
        const templateWxa = await this.model("template_wxa")
            .query(qb => {
                qb.where("template_id", template_id);
            })
            .fetch();

        const app = await this.model("app")
            .forge({
                custom_id: customId,
                template_id: template_id,
                template_wxa_id: templateWxa.id,
                template_industry_id: template_industry_id, // 应用分类id
                name: name, // 应用名称
                info: info, // 应用简介
                started_at: started_at, // 开始时间
                ended_at: ended_at // 结束时间
            })
            .save();

        // 添加地址信息
        await this.model("app_address")
            .forge({
                app_id: app.id,
                province: province, // 省
                city: city, // 市
                district: district // 区
            })
            .save();

        // 创建应用钩子
        this.hook.run("createApp", app);
        this.hook.run("analysis", "app");
        this.success(app);
    }

    /**
     *
     * @api {get} /home/app/templateIndustry 获取应用模版行业
     * @apiDescription 获取应用模版行业
     * @apiGroup Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     *
     * @apiSampleRequest /home/app/templateIndustry
     *
     */
    async templateIndustry() {
        const { templateId } = this.query;
        const templateIndustry = await this.model("template_industry")
            .query(qb => {
                qb.where("template_id", templateId);
            })
            .fetchAll();
        this.success(templateIndustry);
    }

    async _before_templateWxa() {
        await super.isAppAuth();
    }
    /**
     *
     * @api {get} /home/app/templateWxa 获取应用模版小程序主题
     * @apiDescription 获取应用模版小程序主题
     * @apiGroup Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     *
     * @apiSampleRequest /home/app/templateWxa
     *
     */
    async templateWxa() {
        const templateId = this.state.app.template_id;
        const templateWxa = await this.model("template_wxa")
            .query(qb => {
                qb.where("template_id", templateId);
                qb.orderBy("rank", "desc");
            })
            .fetchAll();

        this.success(templateWxa);
    }

    async _before_setTemplateWxa() {
        await super.isAppAuth();
    }
    /**
     *
     * @api {get} /home/app/setTemplateWxa 获取应用模版小程序主题
     * @apiDescription 获取应用模版小程序主题
     * @apiGroup Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     *
     * @apiSampleRequest /home/app/setTemplateWxa
     *
     */
    async setTemplateWxa() {
        const { id } = this.query;
        const appId = this.state.app.id;

        await this.model("app")
            .forge({ id: appId, template_wxa_id: id })
            .save();

        this.success();
    }

    /**
     *
     * @api {get} /home/app/checkWxa 检查当前应用下是否授权小程序
     * @apiDescription 检查当前应用下是否授权小程序
     * @apiGroup Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiSampleRequest /home/app/checkWxa
     *
     */
    async checkWxa() {
        await super.isAppAuth();

        const appId = this.state.app.id;
        const wxa = await this.model("wxa")
            .query(qb => {
                qb.where("app_id", "=", appId);
                qb.where("authorized", "=", 1);
                qb.where("status", "=", 1);
            })
            .fetch();
        if (wxa) {
            this.success(true);
        } else {
            this.success(false);
        }
    }
};
